import 'package:flutter/material.dart';
import 'package:flutter_yn_goods/pages/model_home.dart';
import 'package:get/get.dart';
import 'package:flutter_yn_goods/base/controller/base_list_more_controller.dart';
import 'package:flutter_yn_goods/pages/search/model/search_product_model.dart';
import 'package:flutter_yn_goods/utils/http/http_manager.dart';
import 'package:flutter_yn_goods/utils/shared/shared_pref_util.dart';
import 'package:flutter_yn_goods/utils/log/utils_log.dart';

class SearchLogic extends BaseListMoreController {
  // 搜索框控制器
  final TextEditingController searchController = TextEditingController();

  // 搜索关键词
  final RxString keyword = ''.obs;

  // 搜索历史
  final RxList<String> searchHistory = <String>[].obs;

  // 是否显示搜索结果
  final RxBool showResult = false.obs;

  // 搜索历史存储key
  static const String historyKey = 'search_history';

  // 最大历史记录数
  static const int maxHistoryCount = 10;

  @override
  void onInit() {
    super.onInit();
    loadSearchHistory();
  }

  @override
  void onClose() {
    searchController.dispose();
    super.onClose();
  }

  // 加载搜索历史
  void loadSearchHistory() async {
    final history = await SharedPrefUtil.getStringList(historyKey) ?? [];
    searchHistory.value = history;
  }

  // 保存搜索历史
  void saveSearchHistory(String keyword) async {
    if (keyword.isEmpty) return;

    // 移除相同的关键词（如果存在）
    searchHistory.remove(keyword);
    // 将新关键词添加到列表开头
    searchHistory.insert(0, keyword);

    // 如果超过最大数量，删除最旧的
    if (searchHistory.length > maxHistoryCount) {
      searchHistory.removeLast();
    }

    // 保存到本地存储
    await SharedPrefUtil.setStringList(historyKey, searchHistory);
  }

  // 清空搜索历史
  void clearSearchHistory() async {
    searchHistory.clear();
    await SharedPrefUtil.remove(historyKey);
  }

  // 点击搜索按钮
  void onSearch() {
    final text = searchController.text.trim();
    if (text.isEmpty) return;

    keyword.value = text;
    saveSearchHistory(text);
    showResult.value = true;
    refreshList();
  }

  // 点击历史记录项
  void onHistoryItemTap(String text) {
    searchController.text = text;
    keyword.value = text;
    showResult.value = true;
    refreshList();
  }

  @override
  Future<List> loadData() async {
    // try {
    if (keyword.isEmpty) return [];

    final params = {
      'keyword': keyword.value,
      'page': pageNum,
      'limit': pageSize,
    };

    final response = await HttpManager().get(
      'api/products',
      params: params,
      fromJson: ModelHomeList.fromJson,
    );

    return response.data ?? [];
    // } catch (e) {
    //   clog('搜索商品出错: $e');
    //   return [];
    // }
  }
}
